package semaphore;

public class Semaphore {
	int count;
	/**@param count: The internal counter is set to this value;
	* must be greater or equal to zero. */
	public Semaphore(final int count) {
		if (count < 0) throw new Error();
		this.count = count;
	}
	
	/**If the internal counter is zero, the calling thread must wait here.
	* Otherwise the counter is decremented. */
	public synchronized void down(){
		while (count == 0) {
			try{
				this.wait(); 
			} catch(final InterruptedException e){} 
		}
		count = count - 1; 
	}
	/**Increments the internal counter.
	* If some threads are waiting here,
	* one of them is set alive again.*/
	public synchronized void up () {
		this.count = this.count + 1;
		this.notify();
	}
}